#include <iostream>
#include <algorithm>
#include <vector>
#include <math.h>
using namespace std;
class Solution
{
public:
    int bitwiseComplement(int num)
    {

        // num to binary
        vector<int> res;
        if (0 == num)
        {
            return 1;
        }
        while (num)
        {
            res.push_back(num % 2);
            num /= 2;
        }
        // binary to num
        int size = res.size();
        for (int i = size - 1; i >= 0; i--)
        {
            cout << "temp:" << res[i] * pow(2, i) << endl;
            num += !res[i] * pow(2, i);
        }
        return num;
    }

    int bitwiseComplement_2(int num)
    {

        if (num == 0)
        {
            return 1;
        }

        int i = 0, ans = 0;
        while (num > 0)
        {
            ans += pow(2, i) * (num % 2 == 0 ? 1 : 0);
            i++;
            num /= 2;
        }

        return ans;
    }

    int bitwiseComplement_3(int num)
    {
        int m = num;
        int mask = 0;
        // edge case
        if (num == 0)
        {
            return 1;
        }

        while (m)
        {
            mask = (mask << 1) | 1;
            // m/2
            m >>= 1;
        }
        return ~num & mask;
    }
};
int main(int argc, char const *argv[])
{
    Solution s;
    cout << s.bitwiseComplement_3(7) << endl;
    return 0;
}
